<template>
  <div class="app-container">
    <common-table
      :colnames="colnames"
      :list-data="listData"
      :list-loading="listLoading"
      :is-multiple="isMultiSelect"
      :buttons="buttons"
      :custom-buttons="customButtons"
      :custom-selectors="customSelectors"
      :query="routeQuery"
      @fetchData="fetchData"
      @itemNew="itemNew"
      @itemEdit="itemEdit"
      @itemDelete="itemDelete"
      @onItemClick="onItemClick"
      @onCustomButtonClick="onCustomButtonClick"
    >
      <template v-slot:default>
        <div class="station-info">
          <div class="left">
            <el-row>
              <el-col>
                <svg-icon style="width: 64px; height: 64px;" icon-class="dashboard" />
              </el-col>
            </el-row>
          </div>
          <div class="right">
            <el-row>
              <el-col class="t1">
                场站：{{ stationName }}

                <span style="float:right">
                  <el-button
                    type="primary"
                    size="mini"
                    style="margin-right: 15px;"
                    @click="manageSection"
                  >
                    管理分区
                  </el-button>
                  <el-switch
                    v-model="stationStatus"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    active-text="启用"
                    inactive-text="禁用"
                    @change="onStationStatusChange"
                  />
                </span>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8" class="t2"><span class="bold">创建时间：</span>{{ station.createDate | formatDateHM }}</el-col>
              <el-col :span="8" class="t2"><span class="bold">地址：</span>{{ station.addrDesc }}</el-col>
              <el-col :span="8" class="t2"><span class="bold">分区数量：</span>{{ station.sectionCount || 0 }}</el-col>
            </el-row>
            <el-row>
              <el-col :span="8" class="t2"><span class="bold">备注：</span>{{ station.remark }}</el-col>
              <el-col :span="8" class="t2"><span class="bold">更新时间：</span>{{ station.createDate | formatDateHM }}</el-col>
              <el-col :span="8" class="t2"><span class="bold">价格牌数量：</span>{{ listData.total }}</el-col>
            </el-row>
          </div>
        </div>
      </template>
      <template v-slot:rightPannel>
        <!-- <el-button size="mini" type="default" @click="downloadTemplate()">下载模板</el-button>
          <el-button size="mini" type="primary" style="margin-right:80px;" @click="importData()">批量导入</el-button> -->
        <el-input v-model="listQuery.devName" placeholder="价牌名称" clearable class="etag" size="mini" />
        <el-input v-model="listQuery.templateId" placeholder="价格编号" clearable class="etag" size="mini" />
        <el-input v-model="listQuery.devIMEI" placeholder="价牌IMEI" clearable class="etag" size="mini" />
        <el-button type="primary" size="mini" class="ml5" @click="fetchData(listQuery)">查询</el-button>
        <el-button type="default" size="mini" class="ml5" @click="exportData(listQuery)">导出</el-button>
      </template>
    </common-table>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="40%"
      destroy-on-close
    >
      <common-edit
        :fields="editCols"
        :edit-type="editType"
        :values="editValues"
        :rules="editRules"
        @onCancel="dialogVisible = false"
        @onSubmit="onSubmit"
      />
    </el-dialog>

  </div>
</template>
<style scoped>
.el-row {
  margin-bottom: 10px;
}
.left {
  position: fixed;
  width: 100px;
  margin: 20px;
}
.right {
  width: 100%;
  padding-left: 120px;
}
.t1 {
  font-size: 1.5em;
  margin-top: 10px;
  margin-bottom: 10px;
}
.t2 {
  font-size: 1.0em;
}
.bold {
  font-weight: bold;
}
.station-info{
  margin-bottom: 20px;
}
.etag {
  width: 150px;
  margin-right:5px;
}
</style>
<script>
import { mapGetters } from 'vuex'
import CommonTable from '../commontable'
import CommonEdit from '../commontable/edit'
import { getEtagList, delEtag, addEtag, putEtag, exportEtag } from '@/api/etag'
import { batchDel, mergeQuerrys } from '@/utils'
import { putStation, getStation } from '@/api/station'
export default {
  name: 'Detail',
  components: { CommonTable, CommonEdit },
  data() {
    return {
      station: {
      },
      stationStatus: true,
      customSelectors: [
        // { name: 'opt1', options: [
        //   { name: 'select1', value: '1' },
        //   { name: 'select2', value: '2' }
        // ] }
      ],
      buttons: [
        { name: '新建价牌' },
        { name: '修改' },
        { name: '删除' }
      ],
      customButtons: [
        { name: '读取状态', type: 'default', data: {}}
        // { name: '下载模板', type: 'default', data: {}},
        // { name: '批量导入', type: 'primary', data: {}}
      ],
      colnames: [
        { displayName: '序号', colName: 'id', colWidth: '64px', sortable: false },
        { displayName: '价牌名称', colName: 'devName', sortable: false },
        { displayName: '所属分区', colName: 'section.sectionName', sortable: false },
        // { displayName: '价牌编号', colName: 'templateId', sortable: false, queryable: true },
        { displayName: '显示价格', colName: 'usingTemplate.fileUrl', dataType: 'image', colWidth: '120px', sortable: false },
        { displayName: '设定价格', colName: 'settingTemplate.fileUrl', dataType: 'image', colWidth: '120px', sortable: false },
        { displayName: '同步状态', colName: 'syncStatus', sortable: false, formater: (val, row) => {
          return row.usingTemplate && row.settingTemplate && row.usingTemplate.otaId === row.settingTemplate.otaId ? '是' : '否'
        } },
        { displayName: '在线状态', colName: 'devStatus', sortable: false },
        { displayName: '价牌IMEI编号', colName: 'devIMEI', sortable: false },
        { displayName: '价牌类型', colName: 'priceTypeDesc', sortable: false },
        { displayName: '信号数值 ', colName: 'devRSSI', sortable: false },
        { displayName: '设备电压 ', colName: 'devBat', sortable: false },
        {
          displayName: '操作', dataType: 'oprators', data: {
            ops: [
              { name: '编辑', click: 'itemUpdate' }, { name: '删除', click: 'itemDelete' }
            ]
          }
        }
        // { displayName: '价牌Id', colName: 'templateId', dataType: 'imglink', link: { name: 'priceDetail' }, colWidth: '120px' },

        // { displayName: '设备ID', colName: 'devId', sortable: false, hidden: true },
        // { displayName: 'RSSI', colName: 'devRSSI', sortable: false },
        // { displayName: '所属场站', colName: 'station.stationName', sortable: false },
        // { displayName: '所属车位', colName: 'place.placeName', sortable: false }
      ],
      editCols: [
        { displayName: 'ID', colName: 'id', readOnly: true },
        { displayName: '价牌名称', colName: 'devName' },
        { displayName: '所属分区', colName: 'sectionId', dataType: 'fromapipage', data: { name: 'section', queryWith: ['stationId'] }},
        { displayName: '价格类型', colName: 'priceType', dataType: 'select', data: { options: [
          { name: '一口价', value: 1 },
          { name: '分时价', value: 2 }
        ] }},
        { displayName: '价格', colName: 'templateId', dataType: 'fromapipage', data: { name: 'price' },
          withCreateButton: { name: '新建', onclick: ({ item, form }) => {
            console.log('新建价牌', item, form)
          } }},
        { displayName: 'IMEI号', colName: 'devIMEI' },
        { displayName: '电池类型', colName: 'batType', dataType: 'select', data: {
          options: [
            { name: '锂电池', value: 1 },
            { name: '干电池', value: 2 },
            { name: '常供电', value: 3 }]
        }},
        // { displayName: 'sim卡号', colName: 'devCCID' },
        { displayName: '备注', colName: 'remark', dataType: 'textarea' }
        // { displayName: '设备Id', colName: 'devId' },

        // { displayName: '所属场站', colName: 'stationId', dataType: 'fromapipage', data: { name: 'station' }},
        // { displayName: '所属车位', colName: 'placeId', dataType: 'fromapipage', data: { name: 'place', queryWith: ['sectionId'] }}
      ],
      editType: 'edit',
      editValues: {},
      listData: {},
      editRules: {
        'devId': [{ required: true, trigger: 'blur', message: '不能为空' }],
        'devIMEI': [{ required: true, trigger: 'blur', message: '不能为空' }],
        'devName': [{ required: true, trigger: 'blur', message: '不能为空' }],
        'priceType': [{ required: true, trigger: 'blur', message: '不能为空' }],
        'templateId': [{ required: true, trigger: 'blur', message: '不能为空' }],
        'stationId': [{ required: true, trigger: 'blur', message: '不能为空' }]
      },
      listLoading: false,
      isMultiSelect: true,
      dialogVisible: false,
      dialogTitle: '新建',
      stationName: '---',
      listQuery: {}
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'name',
      'avatar',
      'roles'
    ]),
    routeQuery() {
      return this.$route.params.query
    },
    routeStationId() {
      return this.$route.params.stationId
    },
    fromItem() {
      return this.$route.params.fromItem
    }
  },
  created() {
  },
  mounted() {
    this.$nextTick(() => {
      // 如果从路由传过数据来了，就直接采用
      if (this.$route.params.fromItem) {
        if (this.$route.params.stationName) {
          this.stationName = this.$route.params.stationName
        }
        if (this.$route.params.fromItem) {
          this.station = Object.assign(this.station, this.$route.params.fromItem)
        }
        this.stationStatus = (this.station.stationStatus === 1)
      } else {
      // 没传数据，比如浏览器刷新了，就重新获取当前的场站信息
        getStation(this.routeStationId).then(ret => {
          console.log('station:', ret)
          this.station = ret.data
          this.stationName = this.station.stationName
          this.stationStatus = (this.station.stationStatus === 1)
        })
      }
    })
  },
  methods: {
    fetchData(listQuery) {
      this.listQuery = listQuery
      console.log('fetchData', listQuery)
      this.listLoading = true
      const keyDefs = [
        { key: 'devName', matchType: 'like' },
        { key: 'templateId', matchType: 'like' },
        { key: 'devIMEI', matchType: 'like' }
      ]

      getEtagList(mergeQuerrys(keyDefs, listQuery), this.$route.params.stationId)
        .then(ret => {
          console.log('ret', ret)
          this.listData = ret.data
        }).finally(() => {
          this.listLoading = false
        })
    },
    itemNew() {
      console.log('etag New', this.$route.params.stationId)
      this.editType = 'add'
      this.dialogTitle = '新建'
      this.editValues = {
        stationId: this.$route.params.stationId
      }
      this.dialogVisible = true
    },
    itemEdit({ type, item, items }) {
      console.log('itemEdit')
      this.editType = 'edit'
      this.editValues = item
      this.dialogTitle = '修改'
      this.dialogVisible = true
    },
    itemDelete({ type, item, items }) {
      console.log('itemDelete')
      if (type === 'one') {
        delEtag({ etagId: item.id }).then(ret => {
          this.$message({
            type: 'success',
            message: '删除成功！'
          })
          this.fetchData(this.listQuery)
        })
      } else if (type === 'multi') {
        batchDel(delEtag, items, { idname: 'etagId', idvalue: 'id' }).then(ret => {
          this.$message({
            type: 'success',
            message: '删除成功！'
          })
          this.fetchData(this.listQuery)
        })
      }
    },
    onSubmit(formData) {
      console.log('onSubmit', formData)
      if (this.editType === 'add') {
        // 新建
        addEtag(formData).then((ret) => {
          console.log('add ret', ret)
          this.$message({
            type: 'success',
            message: '添加成功！'
          })
          this.dialogVisible = false
          this.fetchData(this.listQuery)
        })
      } else {
        // 修改
        putEtag(formData).then((ret) => {
          console.log('edit ret', ret)
          this.$message({
            type: 'success',
            message: '修改成功！'
          })
          this.dialogVisible = false
          this.fetchData(this.listQuery)
        })
      }
    },
    onItemClick({ col, row }) {
      // 点击事件
      if (col.link) {
        if (col.link.name === 'priceDetail') {
          // 价格牌详情
          console.log('priceDetail', row)
        }
      }
    },
    onStationStatusChange(val) {
      console.log(996, val)
      putStation({
        id: this.fromItem.id,
        stationStatus: val ? 1 : 0
      }).then(ret => {
        console.log(ret)
      })
    },
    onCustomButtonClick({ target, data }) {
      console.log(target.name, '点击了')
      switch (target.name) {
        case '读取状态':
          this.fetchData(this.listQuery)
          break
        case '下载模板':
          break
        case '批量导入':
          break
      }
    },
    exportData(listQuery) {
      listQuery.stationId = this.$route.params.stationId
      const keyDefs = [
        { key: 'devName', matchType: 'like' },
        { key: 'templateId', matchType: 'like' },
        { key: 'devIMEI', matchType: 'like' },
        { key: 'stationId', matchType: 'match' }
      ]

      exportEtag(mergeQuerrys(keyDefs, listQuery)).then(ret => {
        console.log(ret)
      })
    },
    manageSection() {
      this.$router.push({ name: 'Section', params: { stationId: this.station.id, stationName: this.station.stationName }})
    }
  }

}
</script>
